package org.timeticker;

import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

/**
 * A Helper class to simplify the usage of XPath on xml data
 * 
 * @author  IvanLatysh
 * @version 0.1
 * @since   October 25, 2006
 */
public class XPathHelper {

  /**
   * Evaluate given XPath against given XML and return result as an Integer
   *
   * @param  xml xml data
   * @param  xpathExp xpath expression
   * @return XPath result or null
   * @throws NumberFormatException when unable to convert XPath result into an integer
   * @throws IllegalArgumentException for invalid xpath expression
   */
  public static Integer getInteger(String xml, String xpathExp) {
    return Integer.valueOf(getString(xml, xpathExp));
  }

  /**
   * Evaluate given XPath against given XML and return result as a Double
   *
   * @param  xml xml data
   * @param  xpathExp xpath expression
   * @return XPath result or null
   * @throws NumberFormatException when unable to convert XPath result into a Double
   * @throws IllegalArgumentException for invalid xpath expression
   */
  public static Double getDouble(String xml, String xpathExp) {
    return Double.valueOf(getString(xml, xpathExp));
  }

  /**
   * Evaluate given XPath against given XML and return result as a Double
   *
   * @param  xml xml data
   * @param  xpathExp xpath expression
   * @param  dateFormat date format
   * @return XPath result as a date or null
   * @throws ParseException when unable to parse the data
   */
  public static Date getDate(String xml, String xpathExp, String dateFormat) throws ParseException {
    String strValue = getString(xml, xpathExp);
    if (strValue!=null) return null;
    return new SimpleDateFormat(dateFormat).parse(strValue); 
  }
  
  
  /**
   * Evaluate given XPath against given XML and return result as a String
   *
   * @param  xml xml
   * @param  xpathExp xpath expression
   * @return result string or null
   * @throws IllegalArgumentException when xpath expression is invalid
   */
  public static String getString(String xml, String xpathExp) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
      return xpath.evaluate(xpathExp, new InputSource(new StringReader(xml)));
    } catch (XPathExpressionException e) {
      throw new IllegalArgumentException("Invalid xpath expression {"+xpathExp+"}",e);
    }
  }

}
